package com.xcyy.zjdxmjk.zjdxmjk.controller;

import com.xcyy.zjdxmjk.zjdxmjk.VO.ResultVO;
import com.xcyy.zjdxmjk.zjdxmjk.VO.TownVO;
import com.xcyy.zjdxmjk.zjdxmjk.VO.XzqVO;
import com.xcyy.zjdxmjk.zjdxmjk.common.ResultVOUtil;
import com.xcyy.zjdxmjk.zjdxmjk.entity.Town;
import com.xcyy.zjdxmjk.zjdxmjk.entity.UserInfo;
import com.xcyy.zjdxmjk.zjdxmjk.service.TownService;
import com.xcyy.zjdxmjk.zjdxmjk.service.UserInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class TownController {
    @Autowired
    private TownService townService;
    @Autowired
    private UserInfoService userInfoService;

    @PostMapping("addtown")
    private ResultVO addTown(Town town){
        Town result=townService.save(town);
        if (result==null)
        {
            return ResultVOUtil.error(400,"添加失败");
        }

        return ResultVOUtil.success(result);

    }
    @PostMapping("/findmytowns")
    private ResultVO findmytowns(String userid){

        UserInfo userInfo=userInfoService.findByUserid(userid);
        if (userInfo==null){
            return ResultVOUtil.error(400,"没有找到该用户");
        }
        if (!"1".equals(userInfo.getPosition())){
            return ResultVOUtil.error(401,"你没有录入权限");
        }

        List<TownVO> townVOS=new ArrayList<>();
        TownVO townVO;
        List<Town>  towns=townService.findByDept(userInfo.getDepartment());
        for(Town town:towns){
            townVO=new TownVO();
            BeanUtils.copyProperties(town,townVO);
            townVOS.add(townVO);
        }
        return ResultVOUtil.success(townVOS);
    }
    @PostMapping("/edittown")
    private ResultVO edittown(String code,Integer dcjggs){
        Town town=townService.findByCode(code);
        if (town==null){
            return ResultVOUtil.error(400,"没有找到code");
        }
        town.setDcjggs(dcjggs);
        Town result=townService.save(town);
        return ResultVOUtil.success(result);
    }
}
